package RabbitUI.Beta;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import java.io.File;
import java.io.FileFilter;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JToolBar;


import icons.IconTheme;
import IHM.IHM_addon_Alpha;
import JSON.JSONException;
import Nuplet.Pair;
import OsType.OsType;
import RabbitUI.RabbitUIConf;
import RabbitUI.RabbitUtils;
import RabbitUI.Alpha.RabbitUIAlpha;
import RabbitUI.filetype.RabbitUIFileType;
import TextZone.ColoredTextZone;

public class RabbitUIBeta extends RabbitUIAlpha implements IHM_addon_Alpha{

	public final static int FENETRE_EXEC=NBRECT_ALPHA;
	public final static int NBRECT_BETA=NBRECT_ALPHA+1;
	private String commanderin;
	private String commanderout;

	private ColoredTextZone monitor;
	protected OsType os;
	JToolBar toolbar_com;
	public RabbitUIBeta(IconTheme theme, RabbitUIConf conf,OsType sysex) {
		super(theme, conf);
		os=sysex;
		try {
			File a;
			a = File.createTempFile("commandline", ".in");
			commanderin=a.getAbsolutePath();
			a.deleteOnExit();
			a = File.createTempFile("commandline", ".out");
			commanderout=a.getAbsolutePath();
			a.deleteOnExit();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String EXPLICATION1="%file%  = fichier actif";
		String EXPLICATION2="%file.% = fichier actif sans son extension";
		String EXPLICATION3="%open%<fichier a>%nepo%";
		String EXPLICATION4="%keep%  = garder le nom du fichier";

		toolbar_com=new JToolBar();

		toolbar_com.setOrientation(JToolBar.VERTICAL);
		toolbar_com.setFloatable(false);

		monitor=new ColoredTextZone("monitor");

		ArrayList<JComponent> j=new ArrayList<JComponent>();
		JCheckBox b=new JCheckBox("system");
		j.add(newbuttonbar("listbadwords", icons.dico(),false,"tip Enter to exec",new buttonlistbadwords()));

		j.add(newbuttonbar("compile", icons.compiler(),false,"tip Enter to exec",null));
		j.add(newbuttonbar("run", icons.run(),false,"tip Enter to exec",null));

		j.add(new JScrollPane(monitor));

		//	monitor.setText(EXPLICATION1+"\n"+EXPLICATION2+"\n"+EXPLICATION3+"\n"+EXPLICATION4);

		b.addActionListener(new RabbitUtils.toollistener(b,toolbar_com, j,get_toolzone()));

		//	add_to_toolzone(b);
		add_to_toolzone(toolbar_com);

	}
	public JToolBar newbuttonbar(String Commande,ImageIcon icon,boolean floatable,String tip,ActionListener plusexec){
		JTextField tmpfield=new JTextField();

		JToolBar toolbar_tmp=new JToolBar();

		tmpfield.setToolTipText(tip);
		final ActionListener al=new buttonbarLi(tmpfield,Commande,plusexec);
		class addon_key implements KeyListener {
			public void keyPressed(KeyEvent e) {
				switch ((int) e.getKeyCode()) {

				case (int) KeyEvent.VK_ENTER:
					al.actionPerformed(null);
				break;
				}
			}
			public void keyReleased(KeyEvent e) {}
			public void keyTyped(KeyEvent e) {}
		}
		tmpfield.addKeyListener(new addon_key());
		toolbar_tmp.add(RabbitUtils.generate_button_action(icon,al,Commande));
		toolbar_tmp.add(tmpfield);

		toolbar_tmp.setFloatable(floatable);
		return toolbar_tmp;
	}
	class buttonbarLi implements ActionListener{
		JTextField comfield;
		String comexec;
		ActionListener opt;
		buttonbarLi(JTextField field,String Commande,ActionListener plusexec){
			comfield=field;comexec=Commande;
			if (plusexec!=null) opt=plusexec;
		}
		public void actionPerformed(ActionEvent e) {
			if (current!=-1){
				String com=comfield.getText();
				String filename=buffer.getPath();
				String ext=buffer.getFileext();
				if (ext!=null){
					if (com.contentEquals("")){
						try {
							RabbitUIFileType.openFileType(ext);
							com=RabbitUIFileType.getCommande(comexec);
							RabbitUIFileType.closeFileType();
						} catch (JSONException e1) {
							e1.printStackTrace();
						} catch (IOException e1) {
							e1.printStackTrace();
						}
						comfield.setText(com);
					}
				}

				com=com.replace("%file%", filename);
				com=com.replace("%file.%", RabbitUIFileType.minusExt(filename));
				if (com.contains("%keep%")){
					comfield.setText(com);
				}
				com=com.replace("%keep","");

				if (com.contains("%open%")){
					String filid=com.substring(com.indexOf("%open%")+6, com.indexOf("%nepo%"));
					if (!(filid.charAt(0)==File.separatorChar)){
						filid=filename.substring(0,filename.lastIndexOf(File.separator) )+File.separator+filid;
					}
					if (filid.contains("*")){
						regexp_open(filid);
					}else					
						open(filid);
					com=com.replace("%open%","");
					com=com.replace("%nepo%","");
				}
				if (com.contentEquals("")){
					debog("Command skipped");//TODO beep system
				} else {
					debog("exec:"+com);
					exeCom(com);
					if (opt!=null) opt.actionPerformed(null);
					toolbar_com.updateUI();
				}
			}
		}
	}
	public void regexp_open(String regexp_filename){
		String tmpdirname=regexp_filename.substring(0,first_index_of_regexp(regexp_filename));
		int pos=tmpdirname.lastIndexOf("/");
		File dir=new File(regexp_filename.substring(0,pos));
		String rest=regexp_filename.substring(pos+1);
		FileFilter filter= new RegexpFilter(dir,rest);
		File[] files_to_open=dir.listFiles(filter);
		if (files_to_open!=null)
			for (int i=0; i< files_to_open.length;i++) {
				open(files_to_open[i].getAbsolutePath());	
			}
	}
	private int first_index_of_regexp(String regexp_filename){
		return regexp_filename.indexOf("*");
	}
	class RegexpFilter implements FileFilter {
		File directory;
		String prefix;
		String suffix;
		boolean filtre;
		public RegexpFilter(File dir,String regexp_path_from_dir) {
			directory=dir;
			if (regexp_path_from_dir.endsWith("*")&&regexp_path_from_dir.startsWith("*")) filtre=false;
			else {
				filtre=true;
				prefix=regexp_path_from_dir.substring(0,regexp_path_from_dir.lastIndexOf('*'));
				suffix=regexp_path_from_dir.substring(regexp_path_from_dir.lastIndexOf('*')+1);
			}
		}

		public boolean accept(File pathname) {
			if (filtre)
				if (pathname.exists())
					if (pathname.getName().endsWith(suffix)&&pathname.getName().startsWith(prefix))return true;
			return false;
		}
	}
	private void exeCom(String com){



		debog(com);
		String path=buffer.getPath();
		debog("-> exec : "+path +" "+commanderin+ " "+ commanderout);
		Process p;
		try {
			p = os.execute(path,com);
			synchronized (p){
				p.wait();
			}
			monitor.setText(os.getText());

		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}


	}

	class buttonlistbadwords implements ActionListener{
		public void actionPerformed(ActionEvent e) {
			buffer.ColorMapReset();
			String[] errorlist=monitor.getText().split("\n");
			for (int i=0;i<errorlist.length;i++) buffer.addToColorMap(errorlist[i], "largestrikethrough");
			buffer.colorize();
		}
	}
	public void refresh(String t){
		super.refresh(t);
	}
	public void settitre(String gettitre) {
		super.settitre(gettitre);

		String filename=buffer.getName();
		System.out.println("RabbitUIBeta.settitre()");

		if (filename!=null)
		{
			String ext=RabbitUIFileType.findExt(filename);
			debog("."+ext);
			try {


				if (ext!=null){	
					if (RabbitUIFileType.getExt().contains(ext)){
						buffer.setFileext(ext);
						RabbitUIFileType.openFileType(ext);
					}
				}else RabbitUIFileType.openDefaultFileType();

				Hashtable<String,String> ht=RabbitUIFileType.getColormap();
				Collection<Character> cc=RabbitUIFileType.getSeparator();
				Hashtable<String, Pair<String, Pair<String, Boolean>>> delim=RabbitUIFileType.getEnvironment_Delimiters();
				String ignore=RabbitUIFileType.getIgnoreChar();
				if (ignore!= ""){buffer.setIgnoreChar(ignore.charAt(0));monitor.setIgnoreChar(ignore.charAt(0));}
				buffer.setColorMap(ht);
				buffer.setSeparator(cc);
				buffer.setEnvironment_Delimiters(delim);

				monitor.setColorMap(ht);
				monitor.setSeparator(cc);
				monitor.setEnvironment_Delimiters(delim);

				RabbitUIFileType.closeFileType();
			} catch (JSONException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				System.out.println("Type de fichier "+ext +" inconnu");
			}
		}
	}
	protected synchronized void nouvellefenetre(String nouveautitre){
		super.nouvellefenetre(nouveautitre);	
		try {
			RabbitUIFileType.openDefaultFileType();


			Hashtable<String,String> ht=RabbitUIFileType.getColormap();
			Collection<Character> cc=RabbitUIFileType.getSeparator();
			Hashtable<String, Pair<String, Pair<String, Boolean>>> delim=RabbitUIFileType.getEnvironment_Delimiters();
			String ignore=RabbitUIFileType.getIgnoreChar();
			if (ignore!= ""){buffer.setIgnoreChar(ignore.charAt(0));monitor.setIgnoreChar(ignore.charAt(0));}
			buffer.setColorMap(ht);
			buffer.setSeparator(cc);
			buffer.setEnvironment_Delimiters(delim);

			monitor.setColorMap(ht);
			monitor.setSeparator(cc);
			monitor.setEnvironment_Delimiters(delim);

			RabbitUIFileType.closeFileType();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
